import socketserver
import struct
import os
import api_wordsclouds
import time

class FileServer(socketserver.BaseRequestHandler):
    # 处理用户发来的请求
    def handle(self):
        try:
            rec = self.request.recv(1024).decode("utf-8")
            print(rec)
            try:
                rec = eval(rec)
                print(rec[1])
                filepath = api_wordsclouds.get_wordcloud_info(rec[1], rec[2])
                print(filepath)
                f = open(filepath, "rb")
                print("开始发送")
                while True:
                    data = f.read(1024)
                    print(data)
                    if not data:
                        self.request.sendall("finish".encode("utf-8"))
                        print("发送完成")
                        break
                    self.request.sendall(data)
                print("正常退出")
            except:
                print("未知错误")
        except:
            print("断开连接,剔除TCP客户端")
        finally:
            print("1234")

    def setup(self):
        print("开始连接", self.client_address)

    def finish(self):
        print("关闭socktc")
        # self.server.server_close()


def main():
    # 表示在线状态
    print("TCP文件传输服务器启动")
    ip_port = ("127.0.0.1", 6789)
    # server = socketserver.TCPServer(ip_port, ChatServer)
    server = socketserver.ThreadingTCPServer(ip_port, FileServer)
    server.serve_forever()



if __name__ == '__main__':
    main()



